/*
 * @lc app=leetcode.cn id=501 lang=typescript
 *
 * [501] 二叉搜索树中的众数
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function findMode(root: TreeNode | null): number[] {
  const inorder = (root: TreeNode | null) => {
    if (root === null) return;
    inorder(root.left);
    // 统计连续出现相同值的次数
    if (curr.val === root.val) {
      count++;
    } else {
      curr = root;
      count = 1;
    }
    // 值出现次数等于最大次数，相同的众数放入结果
    if (count === maxCount) {
      ans.push(root.val);
      // 值出现的次数大于最大值，清空数组，放入新的众数，并更新最大次数
    } else if (count > maxCount) {
      maxCount = count;
      ans.length = 0;
      ans.push(root.val);
    }
    inorder(root.right);
  };
  const ans: number[] = [];
  let count = 0;
  let maxCount = 0;
  let curr = root;

  inorder(root);

  return ans;
}
// @lc code=end
